package com.jf3q.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jf3q.admin.service.impl.ChapterServiceImpl;
import com.jf3q.admin.service.impl.VideoServiceImpl;
import com.jf3q.admin.utils.vo.AjaxResultVO;
import com.jf3q.common.domain.EduChapter;
import com.jf3q.common.domain.EduVideo;
import com.jf3q.common.sample.Sample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author ASUS
 * @date 2024/4/16
 * @apiNote
 */
@RestController
@RequestMapping("/chapter")
public class ChapterController {

    @Autowired
    ChapterServiceImpl chapterService;

    @Autowired
    VideoServiceImpl videoService;

    @Autowired
    Sample sample;

    @GetMapping("/listByCourseId/{courseId}")
    public AjaxResultVO listByCourseId(@PathVariable String courseId) {
        List<EduChapter> list = chapterService.list(
                new LambdaQueryWrapper<EduChapter>()
                        .eq(EduChapter::getCourseId, courseId)
                        .orderByAsc(EduChapter::getSort));
        for (EduChapter chapter : list) {
            chapter.setVideos(videoService.list(
                    new LambdaQueryWrapper<EduVideo>()
                            .eq(EduVideo::getChapterId, chapter.getId())
                            .orderByAsc(EduVideo::getSort)));
        }
        return AjaxResultVO.success(list);
    }

    @GetMapping("/getById/{id}")
    public AjaxResultVO toUpdate(@PathVariable String id) {
        return AjaxResultVO.success(chapterService.getById(id));
    }

    @PostMapping("/saveOrUpdate")
    public AjaxResultVO saveOrUpdate(@RequestBody EduChapter chapter) {
        return chapterService.saveOrUpdate(chapter) ? AjaxResultVO.success() : AjaxResultVO.error();
    }

    @GetMapping("/delete/{id}")
    public AjaxResultVO delete(@PathVariable String id) throws Exception {
        LambdaQueryWrapper<EduVideo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EduVideo::getChapterId, id);
        List<EduVideo> list = videoService.list(wrapper);
        com.aliyun.vod20170321.Client client = sample.createClient();
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        for (EduVideo video : list) {
            com.aliyun.vod20170321.models.DeleteVideoRequest deleteVideoRequest = new com.aliyun.vod20170321.models.DeleteVideoRequest();
            deleteVideoRequest.setVideoIds(video.getVideoSourceId());
            client.deleteVideoWithOptions(deleteVideoRequest,runtime);
        }
        videoService.remove(wrapper);
        return chapterService.removeById(id) ? AjaxResultVO.success() : AjaxResultVO.error();
    }
}
